<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="用户id" prop="uid">
          <el-input v-model="queryParams.uid" placeholder="请输入用户id" clearable @keyup.enter="handleQuery()" />
        </el-form-item>
        <el-form-item label="审核状态" prop="verify_status">
          <el-select v-model="queryParams.verify_status" placeholder="全部" clearable class="!w-[180px]">
            <el-option label="待审核" :value="1" />
            <el-option label="审核通过" :value="3" />
            <el-option label="未通过" :value="4" />
            <el-option label="撤销" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery()">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row>
        <el-table-column label="id" prop="id" width="70" />
        <el-table-column label="审核状态" prop="verify_status" width="100">
          <template #default="scope">
            <span v-if="scope.row.verify_status == 1">待审核</span>
            <span v-else-if="scope.row.verify_status == 3">审核通过</span>
            <span v-else-if="scope.row.verify_status == 4">未通过</span>
            <span v-else-if="scope.row.verify_status == 5">撤销</span>
          </template>
        </el-table-column>
        <el-table-column label="发票类型" prop="verify_status" width="100">
          <template #default="{ row }">
            <span v-if="row.invoice_title_info.invoice_type == 1">个人</span>
            <span v-else>公司</span>
          </template>
        </el-table-column>
        <el-table-column label="发票抬头">
          <template #default="{ row }">
            <div class="text-[13px]">
              <div>{{ row.invoice_title_info.invoice_type == 2 ? '公司名称' : '发票抬头名称' }} : {{ row.invoice_title_info.name
                }}</div>
            </div>
            <template v-if="row.invoice_title_info.invoice_type == 2">
              <div class="text-[13px]">税号: {{ row.invoice_title_info.tax_no }}</div>
              <div class="text-[13px]">公司电话: {{ row.invoice_title_info.company_phone }}</div>
              <div class="text-[13px]">公司注册地址: {{ row.invoice_title_info.company_address }}</div>
              <div class="text-[13px]">开户行: {{ row.invoice_title_info.bank_name }}</div>
              <div class="text-[13px]">开户行卡号: {{ row.invoice_title_info.bank_card_no }}</div>
            </template>
          </template>
        </el-table-column>

        <!-- <el-table-column label="金额" width="800">
         
        </el-table-column> -->

        <el-table-column label="申请时间" align="center" width="180" prop="created_at">
          <template #default="scope">
            {{ formatTimestamp(scope.row.created_at * 1000) }}
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button v-hasPerm="['/admin/invoice/invoiceApply/verify']" v-if="scope.row.verify_status == 1"
              type="primary" size="small" link icon="Document" @click="handleVerify(scope.row)">
              审核
            </el-button>
            <!-- <el-button v-hasPerm="['download:invoice']" v-else-if="scope.row.verify_status == 3" type="primary"
              size="small" link icon="Download" @click="handleDownload(scope.row)">
              下载发票
            </el-button> -->
            <el-button v-hasPerm="['amount:info']" type="primary" size="small" link icon="DocumentCopy"
              @click="handleShowAmount(scope.row)">
              金额详情
            </el-button>
            <el-button v-hasPerm="['amount:info']" type="primary" size="small" link icon="DocumentCopy"
              @click="handleUserInfo(scope.row)">
              户头信息
            </el-button>

            <!-- <el-button v-if="scope.row.rel_type == 1" v-hasPerm="['amount:info']" type="primary" size="small" link
              icon="DocumentCopy" @click="handleBillInfo(scope.row)">
              抄表数据
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page" v-model:limit="queryParams.ps"
        @pagination="handleQuery()" />
    </el-card>

    <!-- 审核 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body @close="handleCloseDialog">
      <el-form ref="formRef" :model="formData" label-width="100px">
        <el-form-item label="审核状态">
          <el-radio-group v-model="formData.verify_status">
            <el-radio :value="3" label="通过" />
            <el-radio :value="4" label="驳回" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核文字" prop="verify_msg">
          <el-input v-model="formData.verify_msg" placeholder="请输入审核文字" />
        </el-form-item>
        <el-form-item v-if="formData.verify_status == 3" label="发票文件" prop="download_url">
          <single-upload tip="可上传图片、pdf、等。" :showTip="true" :accept="'application/pdf, image/*'" :limit="1"
            v-model="formData.download_url" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="amount" title="金额详情" append-to-body @close="handleCloseDialog" width="65%">
      <div class="flex">
        <div class="w-[180px] font-600 p-1" v-for="(item, index) in rowData.preview_data.header" :key="index">
          {{ item }}</div>
      </div>
      <div class="flex mt-2" v-for="(item, index) in rowData.preview_data.body" :key="index">
        <div class="w-[180px] mb-2 p-1" v-for="n in item">{{ n }} </div>
      </div>
    </el-dialog>

    <el-dialog v-model="userInfo" title="户头信息" append-to-body @close="handleCloseDialog" width="65%">
      <div class="font-600 mt-2 mb-1">户头信息</div>

      <el-row :gutter="20">
        <el-col :span="12">
          户主姓名：{{ rowData.water_meter.holder_username }}
        </el-col>
        <el-col :span="12">
          水表编号：{{ rowData.water_meter.code }}
        </el-col>
        <el-col :span="12">
          户主电话：{{ rowData.water_meter.holder_tel }}
        </el-col>
        <el-col :span="12">
          片区名称：{{ rowData.water_meter.area_name }}
        </el-col>
        <el-col :span="12">
          地址：{{ rowData.water_meter.address }}
        </el-col>
      </el-row>

      <template v-if="rowData.rel_type == 1">
        <div class="font-600  mt-2 mb-1">抄表数据</div>
        <el-row :gutter="20">
          <el-col :span="12">
            月份：{{ rowData?.bill?.month }}
          </el-col>
          <el-col :span="12">
            用水量：{{ rowData.bill.consumption }}m³
          </el-col>
          <el-col :span="12">
            起度：{{ rowData.bill.last_number }}
          </el-col>
          <el-col :span="12">
            止度：{{ rowData.bill.new_number }}
          </el-col>
          <el-col :span="12">
            需支付金额：{{ rowData.bill.need_pay_amount }}
          </el-col>
        </el-row>

        <div class="mt-3" v-for="(item, index) in rowData?.bill?.amount_details" :key="index">
          <el-row :gutter="20">
            <el-col :span="12">规则名称： {{ item.name }}</el-col>
            <el-col :span="12">最终收费：{{ item.final_fee }}</el-col>
            <!-- <el-col :span="12">城市运营水费：{{ item.urban_fee }}</el-col> -->
            <!-- <el-col :span="12">城市运营水金额：{{ item.urban_price }}</el-col> -->
            <!-- <el-col :span="12">最终收费价格： {{ item.final_price }}</el-col> -->
            <!-- <el-col :span="12">水资源费：{{ item.resource_fee }}</el-col> -->
            <!-- <el-col :span="12">水资金额：{{ item.resource_price }}</el-col> -->
            <!-- <el-col :span="12">水利工程运营水费： {{ item.conservancy_fee }}</el-col> -->
            <!-- <el-col :span="12">污水处理费： {{ item.sewage_treat_fee }}</el-col> -->
            <!-- <el-col :span="12">水利工程运营金额：{{ item.conservancy_price }}</el-col> -->
            <!-- <el-col :span="12">污水处理金额： {{ item.sewage_treat_price }}</el-col> -->
          </el-row>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Invoice",
  inheritAttrs: false,
});

import meteAPI, { PageVO, metePageQuery } from "@/api/system/order";
import SingleUpload from "@/components/Upload/FileUpload.vue";
import { formatTimestamp } from '@/utils/index';

const queryFormRef = ref(ElForm);
const pageData = ref<PageVO[]>([]);
const formRef = ref(ElForm);
const loading = ref(false);
const total = ref(0);
const rowData = ref<any>({});
const amount = ref(false);
// 分页
const queryParams = reactive<metePageQuery>({
  page: 1,
  ps: 10,
});
// 弹窗
const dialog = reactive({
  visible: false,
  title: "发票审核",
});
// form
const formData = reactive<any>({
  // 订单类型
  verify_status: 3,
  // 订单用户
  verify_msg: "",
});

const handleShowAmount = (row: any) => {
  rowData.value = row
  amount.value = true;
}

const userInfo = ref(false);
const handleUserInfo = (row: any) => {
  rowData.value = row
  userInfo.value = true;
}

// 下载发票
const handleDownload = (row: any) => {
  // 假设你已经有了一个包含图片数据的 Blob 对象
  fetch(row.download_url)
    .then(response => response.blob())  // 获取 Blob 数据
    .then(blob => {
      const url = URL.createObjectURL(blob);  // 创建 Blob 对象的 URL
      const link = document.createElement('a');  // 创建 <a> 标签
      link.href = url;  // 设置链接为 Blob 对象的 URL
      link.download = 'downloaded_image.jpg';  // 设置下载文件名
      link.click();  // 触发点击事件，启动下载
      URL.revokeObjectURL(url);  // 释放创建的 URL
    })
    .catch(error => console.error('图片下载失败:', error));  // 错误处理
}


// 打开弹窗
const handleVerify = (row: any) => {
  rowData.value = row;
  dialog.visible = true;
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  amount.value = false;
  formData.download_url = [];
  userInfo.value = false;
  // formRef.value.resetFields();
  // formRef.value.clearValidate();
}

// 提交表单（防抖）
const handleSubmit = useDebounceFn(() => {
  if (formData.verify_status == 4 && formData.verify_msg == "") {
    ElMessage.warning("驳回审核必须填写审核文字");
    return
  }
  loading.value = true;
  let data = {
    id: rowData.value.id,
    download_url: formData?.download_url.length > 0 ? formData?.download_url[0].url : "",
    verify_msg: formData.verify_msg,
    verify_status: formData.verify_status
  }
  meteAPI.invoiceVerify(data)
    .then(() => {
      ElMessage.success("操作成功");
      handleCloseDialog();
      handleResetQuery();
      formData.verify_msg = ""
    })
    .finally(() => (loading.value = false));

}, 1000);

/** 查询 */
function handleQuery() {
  loading.value = true;
  meteAPI.invoiceApplyList(queryParams)
    .then((data) => {
      pageData.value = data.data;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.page = 1;
  handleQuery();
}

onMounted(() => {
  handleQuery();
});
</script>
